﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyCommon.Seed
{
    public class FrameGenerate
    {
        /// <summary>
        /// 创建控制器
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="connId"></param>
        /// <param name="isMuti"></param>
        /// <param name="tableNames"></param>
        /// <returns></returns>
        public static bool CreateControllers(SqlSugarScope scope, string[] tableNames=null)
        {
            Create_Controller_ClassFileByDbTable(scope, $@"F:\wjaProject\SqlSugarTest\SqlSugarTestDemo\MyApi\Controllers\DbFirst", "MyApi.Controllers", tableNames, "");
            return true;
        }

        /// <summary>
        /// 创建控制器
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="connId"></param>
        /// <param name="strPath"></param>
        /// <param name="strNameSpace"></param>
        /// <param name="tableNames"></param>
        /// <param name="strInterface"></param>
        /// <param name="isMuti"></param>
        /// <param name="isSerializable"></param>
        private static void Create_Controller_ClassFileByDbTable(SqlSugarScope scope,string strPath,string strNameSpace, string[] tableNames,string strInterface,bool isSerializable=false)
        {
            var IDbFirst = scope.DbFirst;
            if(tableNames!=null&&tableNames.Length>0)
            {
                IDbFirst = IDbFirst.Where(tableNames);
            }
            var ls = IDbFirst.IsCreateDefaultValue().IsCreateAttribute().StringNullable()
                   .SettingClassTemplate(p => p =
$@"using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MyCommon.HttpContextUser;
using MyIServices;
using MyModels;
using MyModels.Models;

namespace {strNameSpace}" +
@"{
    /// <summary>
    /// 部门控制器
    /// </summary>
    [Route(""api/[controller]/[action]"")]
    [ApiController]
    [Authorize(""Permission"")]
    public class {ClassName}Controller : BaseApiController
    {
        private readonly I{ClassName}Service _{ClassName}Service;
        private readonly IUser _user;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name=""{ClassName}Service""></param>
        public {ClassName}Controller(I{ClassName}Service {ClassName}Service,IUser user)
        {
            _{ClassName}Service = {ClassName}Service;
            _user = user;
        }

        /// <summary>
        /// 获取列表数据
        /// </summary>
        /// <param name=""page""></param>
        /// <param name=""pageSize""></param>
        /// <param name=""key""></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<PageModel<{ClassName}>>> Get(int page = 1, int pageSize = 10, string key = """")
        {
            var list = await _{ClassName}Service.QueryPage(i=>i.IsDeleted==false&&(i.Name!=null&&i.Name.Contains(key)), page, pageSize, "" Id desc"");
            return Success(list);
        }

        /// <summary>
        /// 添加部门数据
        /// </summary>
        /// <param name=""{ClassName}""></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<MessageModel<string>> Post({ClassName} {ClassName})
        {
            {ClassName}.CreateId =_user.UserId;
            {ClassName}.CreateBy = _user.UserName;
            var id = await _{ClassName}Service.Add({ClassName});
            return id > 0 ? Success(id.ToString(), ""添加成功"") : Fail(""添加失败"");
        }

        /// <summary>
        /// 根据id获取一条数据
        /// </summary>
        /// <param name=""id""></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<MessageModel<{ClassName}>> GetById(long id)
        {
            var data = await _{ClassName}Service.QueryById(id);
            if (data != null) {
                return Success(data, ""获取成功"");
            }
            return Fail<{ClassName}>(""未查找到数据"");
        }

        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name=""{ClassName}""></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<MessageModel<string>>Put({ClassName} {ClassName})
        {
            {ClassName}.ModifyBy = _user.UserName;
            {ClassName}.ModifyId = _user.UserId;
            var res = await _{ClassName}Service.Update({ClassName});
            return res ? Success({ClassName}.Id.ToString(), ""修改成功"") : Fail(""修改失败"");
        }
        /// <summary>
        /// 删除数据
        /// </summary>
        /// <param name=""id""></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(long id)
        {
            if (id <= 0) return Fail(""参数错误"");
            var model = await _{ClassName}Service.QueryById(id);
            model.IsDeleted = true;
            var res = await _{ClassName}Service.Update(model);
            return res ? Success(id.ToString(), ""删除成功"") : Fail(""删除失败"");
        }
    }
}"
                   ).ToClassStringList(strNameSpace);
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach (var item in ls)
            {
                var newKey = "_" + item.Key.First().ToString().ToLower() + item.Key.Substring(1);
                string newValue = item.Value.Replace("_" + item.Key, newKey);
                dict.Add(item.Key, newValue);
            }
            CreateFilesByClassStringList(ls, strPath, "{0}Controller");
        }

        /// <summary>
        /// 生成 model 类
        /// </summary>
        /// <param name="scope"></param>
        /// <param name="strPath"></param>
        /// <param name="strNameSpace"></param>
        /// <param name="tableNames"></param>
        /// <param name="strInterface"></param>
        /// <param name="isSerializable"></param>
        private static void Create_Model_ClassFileByDbTable(SqlSugarScope scope, string strPath, string strNameSpace, string[] tableNames, string strInterface, bool isSerializable = false)
        {
            var IDbFirst = scope.DbFirst;
            if (tableNames != null && tableNames.Length > 0) {
                IDbFirst = IDbFirst.Where(tableNames);
            }

            var ls = IDbFirst.IsCreateAttribute().IsCreateDefaultValue()
                .SettingClassTemplate(i => i = @"
{using}

{namespace} " + strNameSpace + @"
{
    {ClassDescription}
    [SugarTable(""{ClassName}"")]" + (isSerializable ? "\n [Serializable]" : "") + @"
    public class {ClassName} : RootEntityTKey<long>
    {
        
    }
}
");
        }

        /// <summary>
        /// 将文件写入指定的目录中
        /// </summary>
        /// <param name="ls"></param>
        /// <param name="strPath"></param>
        /// <param name="fileTemplate"></param>
        private static void CreateFilesByClassStringList(Dictionary<string, string> ls,string strPath,string fileTemplate)
        {
            foreach (var item in ls) {
                var fileName = $"{string.Format(fileTemplate,item.Key)}.cs";
                var fullFilePath = Path.Combine(strPath,fileName);
                if (!Directory.Exists(strPath)) { 
                    Directory.CreateDirectory(strPath);
                }
                File.WriteAllText(fullFilePath,item.Value,Encoding.UTF8);
            }
        }
    }
}
